package com.hhxyjsj.email;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

public class MailUtils {

	private static Properties p = new Properties();
	private static List<String> emailServerList = new ArrayList<String>();
	private static Logger logger = Logger.getLogger(MailUtils.class);

	static{
		try {
			p.load(new FileInputStream(System.getProperty("user.dir") + "/conf/common.conf"));
			emailServerList = getEmailServerAddress();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getDbHost() {
		return p.getProperty("HOST");
	}

	public static String getDbPort() {
		return p.getProperty("PORT");
	}

	public static  String getDbName() {
		return p.getProperty("DATABASE");
	}

	public static  String getDbUserName() {
		return p.getProperty("USERNAME");
	}

	public static  String getDbPassword() {
		return p.getProperty("PASSWORD");
	}

	public static  int getRandomNum() {
		String randomNum = p.getProperty("RANDOMNUM");
		if(randomNum != null && !"".equals(randomNum)){
			return Integer.parseInt(randomNum);
		}
		return Constants.DEFAULT_RANDOMNUM;
	}

	public static  int getThreadNum() {
		String threadNum = p.getProperty("THREADNUM");
		if(threadNum != null && !"".equals(threadNum)){
			return Integer.parseInt(threadNum);
		}
		return Constants.DEFAULT_THREADNUM;
	}

	public static  long getWaitTime() {
		String waitTime = p.getProperty("WAITTIME");
		if(waitTime != null && !"".equals(waitTime)){
			return Long.parseLong(waitTime);
		}
		return Constants.DEFAULT_WAITTIME;
	}

	public static  int getAddresseeNum() {
		String addresseeNum = p.getProperty("ADDRESSEENUM");
		if(addresseeNum != null && !"".equals(addresseeNum)){
			return Integer.parseInt(addresseeNum);
		}
		return Constants.DEFAULT_ADDRESSEENUM;
	}
	
	public static String getHomePage(){
		String homePage = "";
		if(emailServerList != null && emailServerList.size() > 0){
			homePage = emailServerList.remove(0);
		}
		if(homePage != null && !"".equals(homePage)){
			int lastIndex = homePage.lastIndexOf("/");
			if(lastIndex + 1 != homePage.length()){
				String str = homePage.substring(lastIndex);
				if(".asp".equals(str.substring(str.length() - 4))){
					homePage = homePage.substring(0, lastIndex);
				}
			}
			return homePage;
		}
		return Constants.DEFAULT_HOMEPAGE;
	}
	
	public static String getTestHomePage(){
		String homePage = p.getProperty("TESTHOMEPAGE");
		
		if(homePage != null && !"".equals(homePage)){
			int lastIndex = homePage.lastIndexOf("/");
			if(lastIndex + 1 != homePage.length()){
				String str = homePage.substring(lastIndex);
				if(".asp".equals(str.substring(str.length() - 4))){
					homePage = homePage.substring(0, lastIndex);
				}
			}
			return homePage;
		}
		return Constants.DEFAULT_HOMEPAGE;
	}
	
	public static int getMailServerSendBatch(){
		String batch = p.getProperty("MAILSERVERSENDBATCH");
		if(batch != null && !"".equals(batch)){
			return Integer.parseInt(batch);
		}
		return Constants.DEFAULT_MAILSERVERSENDBATCH;
	}
	
	public static String getTestMailAddr(){
		String testMailAddr = p.getProperty("TESTMAILADDR");
		return testMailAddr;
	}
	
	public static String getMailContent(){
		BufferedReader br = null;
		StringBuffer content = new StringBuffer();
		try {
			br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/conf/content.txt")));
			String str;
			while((str = br.readLine()) != null){
				content.append(str + "\n");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.info(e.toString());
				}
			}
		}		
		return content.toString();
	}
	
	public static String getMailSubject(){
			BufferedReader br = null;
			StringBuffer subject = new StringBuffer();
			try {
				br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/conf/subject.txt")));
				String str;
				while((str = br.readLine()) != null){
					subject.append(str);
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				logger.info(e.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				if(br != null){
					try {
						br.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						logger.info(e.toString());
					}
				}
			}		
			return subject.toString();
	}
	
	/**
	 * 获取可用的邮件服务器地址
	 * @return
	 */
	public static List<String> getEmailServerAddress(){
		List<String> rvt = new ArrayList<String>();
		removeEmailAddressFile();
		List<String> usedList = getUsedEmailServerAddress();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/conf/emailServerAddress.conf")));
			String str;
			while((str = br.readLine()) != null){
				str = str.trim();
				if(!"".equals(str) && !usedList.contains(str)){
					rvt.add(str);
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.info(e.toString());
				}
			}
		}
		return rvt;
	}
	
	/**
	 * 获得当天已经使用过的邮件服务器地址
	 * @return
	 */
	private static List<String> getUsedEmailServerAddress(){
		List<String> rvt = new ArrayList<String>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(new File(System.getProperty("user.dir") + "/output/emailServerAddress" + sdf.format(new Date()))));
			String str;
			while((str = br.readLine()) != null){
				str = str.trim();
				if(!"".equals(str)){
					int lastIndex = str.lastIndexOf("/");
					if(lastIndex + 1 != str.length()){
						String _str = str.substring(lastIndex);
						if(".asp".equals(_str.substring(_str.length() - 4))){
							str = str.substring(0, lastIndex);
						}
					}
					rvt.add(str);
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.info(e.toString());
				}
			}
		}
		return rvt;
	}
	
	public static boolean addUsedEmailServerAddress(String url){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		RandomAccessFile raf = null;
		try{
			File file = new File(System.getProperty("user.dir") + "/output/emailServerAddress" + sdf.format(new Date()));
			if(file != null && !file.exists()){	
				file.createNewFile();
			}		
			raf = new RandomAccessFile(file,"rws");
			long len = raf.length();
			raf.seek(len);
			if(len != 0){
				raf.writeBytes("\n");
			}
			raf.writeBytes(url);		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			logger.info(e.toString());
		} finally{
			if(raf != null){
				try {
					raf.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.info(e.toString());
				}
			}
		}
		return true;
	}
	
	private static boolean removeEmailAddressFile(){
		File file = new File(System.getProperty("user.dir") + "/output");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String exceFileName = "emailServerAddress" + sdf.format(new Date());
		if(file != null && file.isDirectory()){
			File[] files = file.listFiles();
			String fileName;
			for(File f : files){
				fileName = f.getName();
				if(fileName != null && !exceFileName.equals(fileName) && fileName.indexOf("emailServerAddress") != -1){
					f.delete();
				}
			}
		}
		return true;
	}
	
	public static void main(String[] agrs){
//		getHomePage();
//		getMailContent();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//		System.out.println(sdf.format(new Date()));
		
//		removeEmailAddressFile();
		
//		addUsedEmailAddress("http://mail.huangtudi.net/default.asp");
		getUsedEmailServerAddress();
	}
}